﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using static System.Net.Mime.MediaTypeNames;

namespace SimplerFileBrowser
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            // 加载树形视图中的用户文件夹
            LoadUserDirectories();
        }

        private void LoadUserDirectories()
        {
            try
            {
                // 获取用户目录路径
                string userFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);

                // 清空树形视图
                treeViewFolders.Nodes.Clear();

                // 创建根节点
                TreeNode rootNode = new TreeNode(userFolderPath);
                rootNode.Tag = userFolderPath;
                treeViewFolders.Nodes.Add(rootNode);

                // 加载子目录
                LoadSubDirectories(rootNode);

                // 展开根节点
                rootNode.Expand();
            }
            catch (Exception ex)
            {
                MessageBox.Show("加载目录时出错: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void LoadSubDirectories(TreeNode parentNode)
        {
            try
            {
                // 获取父节点对应的目录路径
                string path = parentNode.Tag.ToString();

                // 获取子目录
                DirectoryInfo dirInfo = new DirectoryInfo(path);
                DirectoryInfo[] subDirs = dirInfo.GetDirectories();

                foreach (DirectoryInfo dir in subDirs)
                {
                    // 跳过隐藏目录
                    if ((dir.Attributes & FileAttributes.Hidden) != 0)
                        continue;

                    // 创建子节点
                    TreeNode childNode = new TreeNode(dir.Name);
                    childNode.Tag = dir.FullName;
                    parentNode.Nodes.Add(childNode);
                }
            }
            catch (UnauthorizedAccessException)
            {
                // 用户可能没有访问某些目录的权限，这里忽略这个异常
            }
            catch (Exception ex)
            {
                MessageBox.Show("加载子目录时出错: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void treeViewFolders_BeforeExpand(object sender, TreeViewCancelEventArgs e)
        {
            // 检查节点是否已经加载过
            if (e.Node.Nodes.Count > 0 && e.Node.Nodes[0].Tag == null)
                return;

            // 为每个子节点加载子目录
            foreach (TreeNode node in e.Node.Nodes)
            {
                LoadSubDirectories(node);
            }
        }

        private void treeViewFolders_AfterSelect(object sender, TreeViewEventArgs e)
        {
            // 获取选中节点的路径
            string path = e.Node.Tag.ToString();

            // 显示该路径下的文件和文件夹
            DisplayFilesAndFolders(path);
        }

        private void DisplayFilesAndFolders(string path)
        {
            try
            {
                // 清空列表视图
                listViewFiles.Items.Clear();

                // 获取目录信息
                DirectoryInfo dirInfo = new DirectoryInfo(path);

                // 获取子目录
                foreach (DirectoryInfo dir in dirInfo.GetDirectories())
                {
                    // 跳过隐藏目录
                    if ((dir.Attributes & FileAttributes.Hidden) != 0)
                        continue;

                    // 创建列表项
                    ListViewItem item = new ListViewItem(dir.Name);
                    item.SubItems.Add("文件夹");
                    item.SubItems.Add(dir.LastWriteTime.ToString());
                    item.Tag = dir.FullName;
                    item.ImageIndex = 0; // 文件夹图标索引

                    // 添加到列表视图
                    listViewFiles.Items.Add(item);
                }

                // 获取文件
                foreach (FileInfo file in dirInfo.GetFiles())
                {
                    // 跳过隐藏文件
                    if ((file.Attributes & FileAttributes.Hidden) != 0)
                        continue;

                    // 创建列表项
                    ListViewItem item = new ListViewItem(file.Name);
                    item.SubItems.Add(file.Extension);
                    item.SubItems.Add(file.LastWriteTime.ToString());
                    item.SubItems.Add(FormatFileSize(file.Length));
                    item.Tag = file.FullName;

                    // 如果是XML文件，设置特殊图标
                    if (file.Extension.ToLower() == ".xml")
                    {
                        item.ImageIndex = 2; // XML文件图标索引
                    }
                    else
                    {
                        item.ImageIndex = 1; // 普通文件图标索引
                    }

                    // 添加到列表视图
                    listViewFiles.Items.Add(item);
                }

                // 更新状态栏
                toolStripStatusLabel.Text = "当前路径: " + path;
            }
            catch (UnauthorizedAccessException)
            {
                MessageBox.Show("没有权限访问该目录", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            catch (Exception ex)
            {
                MessageBox.Show("显示文件列表时出错: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private string FormatFileSize(long bytes)
        {
            string[] suffix = { "B", "KB", "MB", "GB", "TB" };
            double dblBytes = bytes;
            int i;

            for (i = 0; i < suffix.Length && bytes >= 1024; i++, bytes /= 1024)
            {
                dblBytes = bytes / 1024.0;
            }

            return String.Format("{0:0.##} {1}", dblBytes, suffix[i]);
        }

        private void listViewFiles_DoubleClick(object sender, EventArgs e)
        {
            // 获取选中的项
            if (listViewFiles.SelectedItems.Count > 0)
            {
                ListViewItem item = listViewFiles.SelectedItems[0];
                string path = item.Tag.ToString();

                // 检查是否是目录
                if (item.SubItems[1].Text == "文件夹")
                {
                    // 查找对应的树节点并选中
                    FindAndSelectNode(treeViewFolders.Nodes, path);
                }
                else if (item.SubItems[1].Text.ToLower() == ".xml")
                {
                    // 打开XML文件并显示内容
                    DisplayXmlContent(path);
                }
            }
        }

        private bool FindAndSelectNode(TreeNodeCollection nodes, string path)
        {
            foreach (TreeNode node in nodes)
            {
                if (node.Tag.ToString() == path)
                {
                    treeViewFolders.SelectedNode = node;
                    return true;
                }

                // 递归检查子节点
                if (FindAndSelectNode(node.Nodes, path))
                    return true;
            }

            return false;
        }

        private void DisplayXmlContent(string xmlFilePath)
        {
            try
            {
                // 创建XML查看器窗体
                XmlViewerForm xmlViewer = new XmlViewerForm(xmlFilePath);
                xmlViewer.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show("解析XML文件时出错: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void refreshToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // 刷新当前选中的目录
            if (treeViewFolders.SelectedNode != null)
            {
                string path = treeViewFolders.SelectedNode.Tag.ToString();
                DisplayFilesAndFolders(path);
            }
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("简单文件浏览器\n版本 1.0\n\n一个简单的文件浏览器，支持XML文件查看。",
                "关于", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }

    public partial class XmlViewerForm : Form
    {
        private string xmlFilePath;

        public XmlViewerForm(string xmlFilePath)
        {
            InitializeComponent();
            this.xmlFilePath = xmlFilePath;
            this.Text = "XML查看器 - " + Path.GetFileName(xmlFilePath);

            // 加载XML文件
            LoadXmlFile();
        }

        private void LoadXmlFile()
        {
            try
            {
                // 创建XML文档
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(xmlFilePath);

                // 清空树形视图
                treeViewXml.Nodes.Clear();

                // 加载XML元素
                LoadXmlNode(xmlDoc.DocumentElement, null);

                // 展开根节点
                if (treeViewXml.Nodes.Count > 0)
                    treeViewXml.Nodes[0].Expand();
            }
            catch (Exception ex)
            {
                MessageBox.Show("加载XML文件时出错: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void LoadXmlNode(XmlNode xmlNode, TreeNode treeNode)
        {
            // 创建节点
            TreeNode newNode;

            if (treeNode == null)
            {
                // 根节点
                newNode = treeViewXml.Nodes.Add(xmlNode.Name);
            }
            else
            {
                // 子节点
                newNode = treeNode.Nodes.Add(xmlNode.Name);
            }

            // 处理属性
            if (xmlNode.Attributes != null)
            {
                foreach (XmlAttribute attr in xmlNode.Attributes)
                {
                    TreeNode attrNode = newNode.Nodes.Add("@" + attr.Name + " = " + attr.Value);
                    attrNode.ForeColor = Color.Blue;
                }
            }

            // 处理文本内容
            if (xmlNode.NodeType == XmlNodeType.Text || xmlNode.NodeType == XmlNodeType.CDATA)
            {
                TreeNode textNode = newNode.Nodes.Add(xmlNode.Value);
                textNode.ForeColor = Color.Green;
            }

            // 递归处理子节点
            foreach (XmlNode childNode in xmlNode.ChildNodes)
            {
                if (childNode.NodeType == XmlNodeType.Element)
                {
                    LoadXmlNode(childNode, newNode);
                }
                else if (childNode.NodeType == XmlNodeType.Text || childNode.NodeType == XmlNodeType.CDATA)
                {
                    // 添加文本内容
                    if (!string.IsNullOrWhiteSpace(childNode.Value))
                    {
                        TreeNode textNode = newNode.Nodes.Add("Text = " + childNode.Value);
                        textNode.ForeColor = Color.Green;
                    }
                }
            }
        }
    }
}